<?php

namespace api\modules\v1\forms;

use common\enums\StatusEnum;
use common\helpers\RegularHelper;
use common\models\common\SmsLog;
use common\models\member\Member;
use common\models\validators\SmsCodeValidator;
use common\models\api\AccessToken;

/**
 * Class UpPwdForm
 * @package api\modules\v1\forms
 * @author jianyan74 <751393839@qq.com>
 */
class UpMobileForm extends \common\models\common\LoginForm
{
    public $mobile;
    public $code;
    public $oldmobile;
    public $group;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['mobile','code','oldmobile','group'], 'required'],
            //['code', SmsCodeValidator::class, 'usage' => SmsLog::USAGE_UP_PWD],
            ['mobile', 'match', 'pattern' => RegularHelper::mobile(), 'message' => '请输入正确的手机号码'],
            ['password', 'validateMobile'],
            [['mobile'], 'eitherOneXt'],// 验证新密码和重复密码是否相等
        ];
    }

    public function attributeLabels()
    {
        return [
            'mobile' => '新手机号',
            'code' => '验证码',
            'newmobile' => '旧手机号',
            'group' => '类型',
        ];
    }

    public function eitherOneXt($attribute, $params, $validator){
        if ($this->oldmobile == $this->mobile) {
            $this->addError($attribute, '新手机号不能和旧手机号相同');
        }
    }

    /**
     * @param $attribute
     */
    public function validateMobile($attribute)
    {
        if (!$this->getUser()) {
            $this->addError($attribute, '找不到用户');
        }
    }

    /**
     * @return Member|mixed|null
     */
    public function getUser()
    {
        if ($this->_user == false) {
            $this->_user = Member::findOne(['mobile' => $this->oldmobile, 'status' => StatusEnum::ENABLED]);
        }

        return $this->_user;
    }
}